package com.newshub.ai.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.stream.Collectors;

/**
 * BI 提示词与表结构提供者
 * 从 resources/ai/bi 下读取配置，提供给 ChatBI 使用
 */
@Slf4j
@Service
public class BiPromptProvider {

    private static final String DEFAULT_PROMPT_PATH = "ai/bi/system-prompt.sql.txt";
    private static final String DEFAULT_SCHEMA_PATH = "ai/bi/schema.json";
    private static final String SUMMARY_PROMPT_PATH = "ai/bi/system-prompt.summary.txt";

    public String loadSystemPrompt() {
        return readClasspathFile(DEFAULT_PROMPT_PATH, "# BI System Prompt 文件未找到\n");
    }

    public String loadSchemaSnapshot() {
        return readClasspathFile(DEFAULT_SCHEMA_PATH, "{\n  \"notice\": \"未提供 schema.json，请补充表结构后重启\"\n}\n");
    }

    public String loadSummaryPrompt() {
        return readClasspathFile(SUMMARY_PROMPT_PATH, "你是一名中文数据分析师，请用中文输出简要洞察。\n");
    }

    private String readClasspathFile(String path, String fallback) {
        try {
            ClassPathResource resource = new ClassPathResource(path);
            if (!resource.exists()) {
                log.warn("BI 配置文件不存在: {}", path);
                return fallback;
            }
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8))) {
                return reader.lines().collect(Collectors.joining("\n"));
            }
        } catch (Exception e) {
            log.error("读取 BI 配置文件失败: {} -> {}", path, e.getMessage());
            return fallback;
        }
    }
}
